package com.wyy.controller;

import com.wyy.error.BusinessException;
import com.wyy.error.EnumBusinessError;
import com.wyy.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-19 21:32
 */
@ControllerAdvice
public class BaseController {
    /**
     * 定义exceptionhandler解决未被controller层吸收的exception
     * 避免在前端页面抛出异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    private Object exceptionHandler(HttpServletRequest request, Exception e) throws BusinessException {
        HashMap<String, Object> responseData = new HashMap();
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            responseData.put("errorCode", businessException.getErrorCode());
            responseData.put("errorMsg", businessException.getErrorMsg());
        } else {
            responseData.put("errorCode", EnumBusinessError.UNKNOWN_ERROR.getErrorCode());
            responseData.put("errorMsg", EnumBusinessError.UNKNOWN_ERROR.getErrorMsg());
        }
        return CommonReturnType.create(responseData, "500");
    }
}

